import { createRouter, createWebHistory } from 'vue-router'
import store from '../store'

const routes = [
  {
    path: '/',
    redirect: '/recommendations'
  },
  {
    path: '/recommendations',
    name: 'Recommendations',
    component: () => import('@/views/Recommendations.vue')
  },
  {
    path: '/profile',
    name: 'Profile',
    component: () => import('@/views/user/Profile.vue'),
    meta:{
      requireAuth: true
    }
  },
  {
    path: '/authorDashboard',
    name: 'AuthorDashboard',
    component: () => import('@/views/author/AuthorDashboard.vue'),
    meta:{
      requireAuth: true
    }
  },
  {
    path: '/detail/:id',
    name: 'detail',
    component: () => import('@/views/utilpage/LearningDetail.vue')
  },
  {
    path: '/publish',
    name: 'publish',
    component: () => import('@/views/author/PublishResource.vue')
  },
  {
    path: '/search',
    name: 'Search',
    component: () => import('@/views/common/Search.vue')
  },
  {
    path: '/dataManager',
    name: 'dataManager',
    component: () => import('@/views/utilpage/DataManager.vue'),
    meta:{
      requireAuth: true
    }
  },
  {
    path: '/applyAuthor',
    name: 'ApplyAuthor',
    component: () => import('@/views/user/BecomeAuthor.vue')
  },
  {
    path: '/login',
    name: 'login',
    component: () => import('@/views/common/Login.vue')
  },
  {
    path: '/register',
    name: 'register',
    component: () => import('@/views/common/Register.vue')
  }
]

const router = createRouter({
  history: createWebHistory(),
  routes
})

router.beforeEach((to, from, next) => {
  if (to.matched.some(record => record?.meta?.requireAuth)) {
    if (store.getters.isAuthenticated) {
      next()
    } else {
      next({
        path: '/login',
        query: { redirect: to.fullPath }
      })
    }
  } else {
    next()
  }
})

export default router